#!/bin/sh
# Copyright (c) 2010, bkil.hu
# This program is free software and can be distributed under the terms of
# the GNU General Public License v2,
# see COPYING for detailed licensing terms.
# created on 2010-12-18 20:06

main() {
    local WAIT=30
    TRAPS="1 2 3 15"
    mk_b1b2
    set_summer_temp
    while true
    do
     set_have_bat
     ckbat
     cktmp
     local MSG="$BATMSG$TMSG"
     [ "$MSG" ] &&
        splash red "$MSG"
     sleep $WAIT
    done
    trap - $TRAPS
}

set_have_bat(){
     grep -q "^present: *no$" /proc/acpi/battery/BAT0/state
     HAVEBAT=$?
}

set_summer_temp(){
    local M=`date +%m`
    if [ $M -ge 4 ] && [ $M -le 9 ]
    then
      SUMMER=5
    else
      SUMMER=0
    fi
}

ckbat() {
    BATMSG=""
    [ $HAVEBAT = 0 ] && return

    local LOWBAT=6500

    local V=`tail -n1 /proc/acpi/battery/BAT0/state |
        sed -n 's/^present voltage: *\([^ ]*\) mV$/\1/ p'`
    if [ -n "$V" ] && [ $V -lt $LOWBAT ]
    then
        BATMSG="BATTERY LOW - $V mV"
    fi
}

mk_b1b2(){
 B1=`mktemp`
 nice seq 1 1500 > $B1 ||exit 1
 B2=`mktemp`
 nice seq 1500 -1 1 > $B2 ||exit 1
 trap "rm $B1 $B2; trap - $TRAPS;exit;" $TRAPS
}

b1(){
 nice aplay $B1
}

b2(){
 nice aplay $B2
}

cktmp() {
    local DELTA=3
    if
     [ $HAVEBAT = 0 ]
    then
     local WARNT0=62
    else
     if
      xset q |
      grep -q "^ *Monitor is Off$"
     then
      # bag mode
      local WARNT0=62
      local DELTA=2
     else
      local WARNT0=57
     fi
    fi
    WARNT=`expr $WARNT0 + $SUMMER`
    MAXT=`expr $WARNT + $DELTA`

    local T=`cat /proc/eee/temperature`
    if [ "0$T" -ge $MAXT ]
    then
        TMSG=" | $T celcius -> suspended"
        splash red "$TMSG"
        for a in `seq 1 7`;do
         b2
         b1
        done
        acpitool -s
        # /etc/acpi/suspend.sh
    elif [ "0$T" -ge $WARNT ]
    then
        b2
        TMSG=" | $T celcius"
    else
        TMSG=""
    fi
}

splash() {
 killall yaf-splash 2>/dev/null
 yaf-splash -bg $1 -text "$2" -timeout 29 \
  -margin 2 -bw 0 -placement top -font "9x15B" -outline 0 &
#  -countdown "`date -d '+10sec' '+%b %d %H:%M:%S %Y'`" \
#  -noseconds \
}

main "$@"
